package com.seven.rsa;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

/**
 * 数字签名
 */
public class SignatureDemo {

    public static void main(String[] args) throws Exception {

        String input="123";

        PublicKey publicKey=RSADemo.getPublicKey("a.pub","RSA");
        PrivateKey privateKey=RSADemo.getPrivateKey("a.pri","RSA");
        //获取数字签名
        String signatureData = getSignature(input, "sha256withrsa", privateKey);
        System.out.println(signatureData);
        //校验签名
        boolean b = verifySignature(input, "sha256withrsa", publicKey, signatureData);
        System.out.println(b);

    }

    /**
     * 校验签名
     * @param input：原文
     * @param algorithm：算法
     * @param publicKey：公钥key
     * @param signatureData：签名的密文
     * @return 校验结果
     */
    private static boolean verifySignature(String input, String algorithm, PublicKey publicKey, String signatureData) throws Exception{
        //获取签名对象
        Signature signature = Signature.getInstance(algorithm);
        //初始化校验
        signature.initVerify(publicKey);
        //传入原文
        signature.update(input.getBytes());
        //校验数据
        return signature.verify(Base64.decode(signatureData));
    }

    /**
     * 生成数字签名
     * @param input:原文
     * @param algorithm：算法
     * @param privateKey：私钥key
     */
    private static String getSignature(String input, String algorithm, PrivateKey privateKey) throws Exception{
        //获取签名对象
        Signature signature = Signature.getInstance(algorithm);
        //初始化签名
        signature.initSign(privateKey);
        //传入原文
        signature.update(input.getBytes());
        //开始签名
        byte[] sign = signature.sign();
        //使用base6进行编码
        return Base64.encode(sign);
    }
}
